package com.modular.snowflake;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@Configuration
public class SnowFlakeConfiguration {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    public static final String SNOW_FLAK_REDIS_KEY = "{}:SNOW_DATA_ID";

    @Bean({"modularSnowflake"})
    public Snowflake snowflake(BusinessServerProvider provider) {
        String serviceName = provider.getServerName();
        String redisKey  = StrUtil.format(SNOW_FLAK_REDIS_KEY,serviceName);
        ValueOperations<String, String> vop = redisTemplate.opsForValue();
        Long dataId = vop.increment(redisKey);
        if (dataId == 2147483647L) {
            redisTemplate.delete(redisKey);
        }
        long centerId = dataId / 32L % 32L;
        long actDataId = dataId % 32L;
        this.logger.warn("推送服务初始化雪花算法，数据中心:{},实例id:{}", centerId, actDataId);
        return new Snowflake(centerId, actDataId);
    }
}
